<?php

/**
 * @package    [PACKAGE_NAME]
 *
 * @author     [AUTHOR] <[AUTHOR_EMAIL]>
 * @copyright  [COPYRIGHT]
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       [AUTHOR_URL]
 */

jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');

require_once(JPATH_ROOT . '/components/com_jcomments/jcomments.class.php');

use Joomla\CMS\MVC\Controller\BaseController;

use EasyWeChat\Factory as WechatFactory;

use Joomla\CMS\Log\Log;

defined('_JEXEC') or die;

/**
 * WxMinipro controller.
 *
 * @package  [PACKAGE_NAME]
 * @since    1.0.0
 */
class WxMiniproControllerWxMinipro extends BaseController
{

    public $config = [
        'app_id' => 'wx9ca2891f028bc46c',
        'secret' => '8a8b4304b35c82d4a2cbb718cfb0c4c9',

        // 下面为可选项
        // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        'response_type' => 'array',

        'log' => [
            'level' => 'debug',
            'file' => __DIR__ . '/wechat.log',
        ],
    ];

    public function display($cachable = false, $urlparams = array())
    {
        echo "hell controller";
        return;
    }

    public function getid()
    {
        $res = [
            'result' =>   -1,


        ];

        $jinput = JFactory::getApplication()->input->getInputForRequestMethod();
        $code = $jinput->get('code');
        if (!$code) {
            echo new json_encode($res);
            jexit();
        }

        $app = WechatFactory::miniProgram($this->config);
        $jinput = JFactory::getApplication()->input->getInputForRequestMethod();
        $response = $app->auth->session($code);
        if (isset($response['openid'])) {
            $data = ['openid' => $response['openid']];
            echo new JResponseJson($data, 'success', false, true);
        } else {
            echo new JResponseJson($response, 'openid get error', true, true);
        }
        jexit();
    }

    public function upimg()
    {
        $files = $this->input->files->get('Filedata', array(), 'array');
        if (!$files) {
            echo new JResponseJson(null, 'file upload fail', true, true);
            jexit();
        }
        $datenow = new JDate('now');
        $filename = $datenow->format('Y_m_d_h_i_s');
        $filepath = JPath::clean(implode(DIRECTORY_SEPARATOR, array(JPATH_ROOT . '/', $filename . ".png")));
        $fileurl = JUri::root() . '/' . $filename . ".png";
        $resup = JFile::upload($files['tmp_name'], $filepath);
        if (!$resup) {
            echo new JResponseJson(null, 'file upload fail', true, true);
            jexit();
        } else {
            $data = [
                'fileurl' => $fileurl
            ];
            echo new JResponseJson(null, $data, false, true);
            jexit();
        }
    }

    public function wxrequest()
    {
        JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_k2/tables');
        $row = JTable::getInstance('K2Item', 'Table');
        $row->title = "title";
        $row->introtext = 'body';
        $row->access = 6;
        $row->catid = 2;

        $row->alias = JHtml::_('date', time(), 'Ymd_His');
        $row->published = 1;
        $row->extra_fields = '[]';
        $row->created = date("Y-m-d H:i:s");
        $row->created_by = 153;
        $row->publish_up = date("Y-m-d H:i:s");
        $row->publish_down = "0000-00-00 00:00:00";
        $row->ordering = $row->getNextOrder("catid = " . (int) $row->catid . " AND trash = 0");
        $row->featured = 0;
        $row->language = "*";

        //var_dump($row);
        //var_dump($row->store());

        $data = [
            'haha' => 'hahavalue'
        ];
        echo json_encode($data);
        jexit();
    }

    public function test()
    {
        Log::addLogger(
            array(
                'text_file' => 'com_helloworld.log.php'
            ),
            Log::ALL,
            array('com_wxminipro')
        );

        Log::add('my error messagewewrwer', Log::ERROR, 'com_wxminipro');

        jexit("test");
    }
    public function testdb()
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        // // Insert columns.
        // $columns = array('user_id', 'profile_key', 'profile_value', 'ordering');

        // // Insert values.
        // $values = array(1001, $db->quote('custom.message'), $db->quote('Inserting a record using insert()'), 1);

        // // Prepare the insert query.
        // $query
        //     ->insert($db->quoteName('#__test'))
        //     ->columns($db->quoteName($columns))
        //     ->values(implode(',', $values));

        // //echo $db->replacePrefix((string) $query);
        // // Set the query using our newly populated query object and execute it.
        // $db->setQuery($query);

        //$db->execute();

        //插入数据
        // $profile = new stdClass();
        // $profile->profile_key = 'custom.message';
        // $profile->profile_value = 'Inserting a record using insert()';
        // $profile->ordering = 10;
        // $db->insertObject('#__test', $profile, 'user_id');
        // var_dump($profile->user_id);

        //更新数据
        // $profile2 = new stdClass();
        // $profile2->user_id = 1003;
        // $profile2->profile_key = '更改后的值';
        // $db->updateObject('#__test', $profile2, 'user_id');
        // var_dump($profile2->user_id);

        // $fields = array(
        //     $db->quoteName('ordering') . ' = 100'
        // );

        // $condition = array(
        //     $db->quoteName('profile_key') . ' = ' . $db->quote('custom.message'),
        // );

        // $query->update($db->quoteName('#__test'))->set($fields)->where($condition);

        // echo $db->replacePrefix((string) $query);

        // $db->setQuery($query);

        // $db->execute();

        $query
            ->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')))
            ->from($db->quoteName('#__test'))
            ->where($db->quoteName('profile_key') . ' LIKE ' . $db->quote('custom.%'))
            ->order('ordering ASC');

        echo $db->replacePrefix((string) $query);

        $db->setQuery($query);

        $results = $db->loadObjectList();

        foreach ($results as $res) {
            foreach ($res as $key => $value) {
                print "$key => $value" . '<br/>';
            }
            echo "<br>";
        }

        jexit();
    }

    public function testaddcom()
    {
        JTable::addIncludePath(JPATH_ROOT . '/administrator/components/com_jcomments/tables');
        $comment = JTable::getInstance('Comment', 'JCommentsTable');

        $comment->object_group = 'com_k2';
        $comment->lang = 'zh-CN';
        $comment->date = date("Y-m-d H:i:s");
        $comment->comment = 'ceshishicesshisceshi';
        $result_com = $comment->store();

        var_dump($result_com);
        jexit();
    }

    public function testJtable()
    {
        JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_wxminipro/tables');
        $row = JTable::getInstance('WxUser', 'Table', array());
        // $res = $row->load(1);
        // $row->id = 2;
        // $row->uname = 'willard';
        // $res = $row->store();
        $res = $row->getIdby('fbd7bae856cab572708306fc5453f6a8e0520ba1');
        var_dump($res);

        // $db = JFactory::getDbo();
        // $qurey = $db->getQuery(true);
        // $qurey->select($db->quoteName('id'))
        //     ->from($db->quoteName('#__wxusers'))
        //     ->where($db->quoteName('openid') . ' = "oLmvm5d-adNg5l8mtLj-N_-uF-Ws"');
        // $db->setQuery($qurey);

        // echo $db->replacePrefix((string) $qurey);

        // $id = $db->loadObjectList();
        // var_dump($id);

        jexit();
    }

    public function testsha1()
    {
        echo sha1('oLmvm5d-adNg5l8mtLj-N_-uF-Ws' . 'zhuameng');
    }
    public function testwxrequest()
    {
        $input = $this->input;
        $skey = $input->get('skey');
        $rawData = $input->get('rawData');

        Log::addLogger(
            array(
                'text_file' => 'com_helloworld.log.php'
            ),
            Log::ALL,
            array('com_wxminipro')
        );

        Log::add($skey . '--' . $rawData, Log::ERROR, 'com_wxminipro');


        //var_dump($code);
        echo json_encode("hahaha");
        jexit();
    }
}
